package com.webblog.controller;

import java.util.HashMap;
import java.util.Map;


import com.webblog.pojo.User;
import com.webblog.service.user.UserService;
import com.webblog.util.JWTUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


@Controller
@RequestMapping("/user")
public class UserController {
	
	private Logger logger = Logger.getLogger(UserController.class);
	
	@Autowired
	private UserService userService;

	@RequestMapping(value = "/login",method = RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> doLogin(@RequestParam("userName") String userName,@RequestParam("password")String password){
		Map<String,Object> resultMap = new HashMap<String, Object>();
		User user = userService.findUserByName(userName);
		if(user!=null)
		{
			if(password.equals(user.getUserPassword())){
				//添加token
				String token = JWTUtil.createToken(user.getUserId(),user.getUserName());
				user.setUserPassword("*********");
				resultMap.put("success",true);
				resultMap.put("msg","用户登录成功");
				resultMap.put("user",user);
				resultMap.put("token",token);
			}
			else {
				resultMap.put("success",false);
				resultMap.put("msg","用户名密码错误");
			}
		}
		else {
			resultMap.put("success",false);
			resultMap.put("msg","用户名不存在");
		}
		return resultMap;
	}

	@RequestMapping(value = "/checkToken",method = RequestMethod.GET)
	@ResponseBody
	public Boolean checkToken(HttpServletRequest request){
		String token = request.getHeader("token");
		return JWTUtil.checkToken(token);
	}
}
